<template>
  <div class="container">
    <uv-loading-page :loading="loading" loading-text="加载中..." font-size="24rpx"></uv-loading-page>

    <uv-swiper :list="info.coverUrl" :height="bannerHeight"></uv-swiper>
    <div class="info">
      <div class="title bold">{{info.name}}</div>
      <div class="price flex alignBaseline">
        价格：
        <div class="newPriceBox flex alignBaseline" v-if="newPrice>0">
          <div class="newPrice">¥{{newPrice}}</div>
          <div class="oldPrice">¥{{info.price}}</div>
        </div>
        <div class="twoPrice flex alignCenter" v-else-if="counter.priceRange(info.lessonContent)">
          <div class="newPrice"><span>¥</span>{{counter.priceRange(info.lessonContent)}}</div>
          <div class="oldPrice"><span>¥</span>{{info.price}}</div>
        </div>
        <div class="price" v-else>
          <span>¥</span>{{info.price}}
        </div>
      </div>

      <!-- 课时内容 -->
      <div class="lessonContent">
        <div class="box" v-for="(item,index) in lessonContent" :key="index" @click="selectLesson(index)" :class="{'active':active_format(item,index),'prediction':item.estimateSignUp==1}">{{item.name}}</div>
      </div>

      <div class="tips" v-if="showCanSelect">请选择 {{showCanSelect}} 项课程</div>

      <div class="time fz14">总计课时：{{info.courseDuration}}</div>

      <div class="time fz14" style="margin-top: 10px;" v-if="lessonContent&&lessonContent[0].courseAmount">班级人数：{{lessonContent&&lessonContent[0].courseAmount}}</div>
    </div>

    <view class="courseIntro" v-if="info.intro">
      <view class="title bold">课程详情</view>
      <uv-parse :content="info.intro"></uv-parse>
    </view>

    <view class="actionBtn flex alignCenter justifyBetween">
      <view class="icons flex alignCenter">
        <view class="icon" @click="instance.refs.callServerRef.open(info)">
          <uv-icon name="server-man" size="25" color="#000000"></uv-icon>
        </view>
        <view class="icon">
          <uv-button openType="share" iconSize="25" icon="share" :custom-style="shareStyle"></uv-button>
        </view>
        <view class="icon" @click="proxy.$refs.popup.open()" v-if="info.contactQrCode">
          <uv-icon name="weixin-circle-fill" size="25" color="#41D368"></uv-icon>
        </view>
      </view>
      <div class="btn" :style="{background:'#A0CBD1'}" v-if="info.hasOwnProperty('isEffective')&&info.isEffective==0">该课程已截止报名</div>
      <div class="btn" @click="save" v-else>立即报名</div>
    </view>

    <loginPop ref="loginPopRef"></loginPop>

    <callServer ref="callServerRef"></callServer>

    <getPhonePop ref="getPhonePopRef"></getPhonePop>

    <uv-back-top :scroll-top="scrollTop"></uv-back-top>

    <uv-popup ref="popup" round="10">
      <view class="contactQrCode-image">
        <image :src="info.contactQrCode" mode="widthFix" />
      </view>
    </uv-popup>
  </div>
</template>

<script setup lang="ts">
import getPhonePop from "@/components/main/getPhonePop.vue";
import callServer from "@/packagePages/components/callServer.vue";
import loginPop from "@/packagePages/components/loginPop.vue";
const { proxy } = getCurrentInstance();
import useCounterStore from "@/stores/counter";
const counter = useCounterStore();
const instance = getCurrentInstance();

let id = "";
let info = ref({});
let names = ref([]);
let bannerHeight = ref(0);
let loading = ref(false);
let scrollTop = ref(0);

let lessonContent = computed(() => {
  if (proxy.$utils.isEmptyObject(info.value)) return;
  let lessonContent = info.value.lessonContent;
  let arr = [];
  lessonContent.forEach((element) => {
    if (element.isShow == 1) arr.push(element);
  });
  return arr;
});

let shareStyle = computed(() => {
  return {
    borderWidth: "0 !important",
    height: "auto",
  };
});

let showCanSelect = computed(() => {
  let { lessonContentMin } = info.value;
  if (!lessonContentMin) return null;
  let num = 1;
  if (lessonContentMin) num = lessonContentMin;
  return num;
});

//是否有预付款金额
let signUpPrice = computed(() => {
  if (!info.value.lessonContent) return;
  let { lessonContent } = info.value;
  let amount = 0;
  lessonContent.forEach((element) => {
    if (element.estimateSignUp == 1) amount += Number(element.signUpPrice);
  });
  return amount;
});

let newPrice = computed(() => {
  if (proxy.$utils.isEmptyObject(info.value)) return;
  let lessonContent = [...info.value.lessonContent];
  let amount = 0;
  lessonContent.forEach((element) => {
    //如果有选中或者默认选中
    if (element.isSelect == 1 || element.isDefault) {
      amount += Number(element.discountPrice);
    }
  });
  return amount;
});

//选中的课程 - 不算预付款项
let isSelectCourse = computed(() => {
  let arr = [];
  if (!info.value.lessonContent) return;
  let { lessonContent } = info.value;
  for (let index = 0; index < lessonContent.length; index++) {
    const element = lessonContent[index];
    if (element.isDefault && !element.estimateSignUp) {
      arr.push(element);
    } else if (element.isSelect == 1) {
      arr.push(element);
    }
  }
  return arr;
});

//实际传给接口的选中课程
let isSelectCourseParams = computed(() => {
  let arr = [];
  if (!info.value.lessonContent) return;
  let { lessonContent } = info.value;
  for (let index = 0; index < lessonContent.length; index++) {
    const element = lessonContent[index];
    if (element.estimateSignUp) {
      //预报名
      arr.push(element);
    } else if (element.isDefault) {
      //默认选中
      arr.push(element);
    } else if (element.isSelect == 1) {
      arr.push(element);
    }
  }
  return arr;
});

onPageScroll((e) => {
  scrollTop.value = e.scrollTop;
});

onLoad(async (e) => {
  console.log("课程详情", e);
  id = e.scene || e.id;
  // #ifdef H5
  if (counter.getUrlCode("code")) {
    let resp = await counter.toLogin();
    if (resp) {
      instance.refs.loginPopRef.open();
    } else {
      proxy.$utils.showToast("登录成功");
    }
  }
  // #endif

  await getInfo();
});

onShow(() => {
  counter.init();
});

onShareAppMessage(() => {
  return {
    title: info.value.name, //分享的标题
    path: `/packagePages/curriculum/details?id=${id}`, //点击分享链接之后进入的页面路径
    imageUrl: info.value.coverUrl[0], //分享发送的链接图片地址
  };
});

onShareTimeline(() => {
  return {
    title: info.value.name, //分享的标题
    path: `/packagePages/curriculum/details?id=${id}`, //点击分享链接之后进入的页面路径
    imageUrl: info.value.coverUrl[0], //分享发送的链接图片地址
  };
});

//设置默认选中哪个课程
function setSelectDefault() {
  let lessonContent = [...info.value.lessonContent];
  console.log("课程详情", lessonContent);
  let list = [];
  lessonContent.forEach((element) => {
    if (element.isDefault) list.push(element);
  });
  if (!list.length) info.value.lessonContent[0].isSelect = 1;
}

function save() {
  if (!counter.isLogin) {
    // #ifdef H5
    return counter.toLogin();
    // #endif

    // #ifdef MP-WEIXIN
    return instance.refs.getPhonePopRef.open();
    // #endif
  }

  if (!isSelectCourse.value.length)
    return proxy.$utils.showToast("请选择课程", 0);

  //获取选中的课程
  let selectNum = isSelectCourse.value.length;
  if (showCanSelect.value) {
    if (showCanSelect.value != selectNum)
      return proxy.$utils.showToast(`请选择${showCanSelect.value}项课程`, 0);
  }

  info.value.selectLesson = isSelectCourseParams.value; //选中的课程
  info.value.newPrice = newPrice.value; //需要支付的金额
  if (signUpPrice.value) info.value.signUpPrice = signUpPrice.value; //预付款金额
  counter.ycMpParams.curriculumInfo = info.value;
  proxy.$utils.toLink("/packagePages/curriculum/enterUserInfo");
}

function active_format(item, index) {
  if (item.isDefault) return true;
  return item.isSelect == 1;
}

async function getInfo() {
  try {
    loading.value = true;
    let resp = await proxy.$apis.getCurriculum();

    info.value = await proxy.$apis.webCourse({
      type: "details",
      data: { _id: id },
    });

    console.log("课程信息", info.value);

    let type = [...info.value["type"]];
    let arr = [];
    type.forEach((element) => {
      let index = proxy.$utils.findIndexByField(resp, "_id", element);
      arr.push(resp[index].name);
    });
    names.value = [...arr];
    await getBannerInfo();
    setSelectDefault();
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

async function getBannerInfo() {
  let { width, height } = await proxy.$auth.getImageInfo(
    info.value.coverUrl[0]
  );
  bannerHeight.value = calculateAspectRatioHeight(
    width,
    height,
    counter.windowWidth
  );
  console.log("轮播图高度", bannerHeight.value);

  function calculateAspectRatioHeight(
    originalWidth,
    originalHeight,
    targetWidth
  ) {
    const aspectRatio = originalWidth / originalHeight;
    const targetHeight = targetWidth / aspectRatio;
    return targetHeight;
  }
}

function selectLesson(index) {
  if (info.value.lessonContent[index].isDefault) return;
  if (info.value.lessonContent[index].estimateSignUp == 1) return;
  //如果只能选择一个
  if (showCanSelect.value == 1) {
    info.value.lessonContent.forEach((element) => {
      element.isSelect = 0;
    });
  }
  if (info.value.lessonContent[index].hasOwnProperty("isSelect")) {
    if (info.value.lessonContent[index].isSelect == 1) {
      info.value.lessonContent[index].isSelect = 0;
    } else {
      info.value.lessonContent[index].isSelect = 1;
    }
  } else {
    info.value.lessonContent[index].isSelect = 1;
  }
  if (
    showCanSelect.value &&
    isSelectCourse.value.length > showCanSelect.value
  ) {
    let id = info.value.lessonContent[index].id;
    let current = null;
    for (let idx = 0; idx < isSelectCourse.value.length; idx++) {
      const element = isSelectCourse.value[idx];
      if (
        current == null &&
        element.isSelect == 1 &&
        !element.isDefault &&
        element.id != id
      )
        current = idx;
    }
    if (current != null) info.value.lessonContent[current].isSelect = 0;
  }
}
</script>



<style lang="scss" scoped>
.container {
  padding-bottom: 80px;
  .contactQrCode-image {
    width: 60vw;
    margin: auto;
    padding: 15px;
  }
  .info {
    padding: 15px;
    .title {
      font-size: 16px;
      color: #3c3c3c;
    }
    .price {
      padding: 15px 0 10px;
      font-size: 14px;
      .twoPrice {
        .newPrice {
          color: #ff6600;
          font-size: 28px;
          span {
            font-size: 25px;
          }
        }
        .oldPrice {
          color: #999999;
          text-decoration: line-through;
          margin-left: 10px;
          font-size: 18px;
        }
      }
      .price {
        font-size: 24px;
        font-weight: bold;
        color: #ff6600;
      }
      .oldPriceBox {
        color: #ff6600;
        font-family: "Microsoft YaHei", "微软雅黑";
        font-size: 24px;
        font-weight: bold;
      }
      .newPriceBox {
        .oldPrice {
          margin-left: 15px;
          text-decoration: line-through;
          color: #999999;
          font-size: 16px;
        }
      }
      .newPrice {
        color: #ff6600;
        font-family: "Microsoft YaHei", "微软雅黑";
        font-size: 36px;
        font-weight: bold;
      }
    }
  }
  .lessonContent {
    .box {
      cursor: pointer;
      border: 1px solid #dadde0;
      display: inline-block;
      margin: 0 8px 8px 0;
      padding: 5px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      font-size: 14px;
      color: #11192d;
      border-radius: 6px;
    }
    .active {
      border-color: #f55004 !important;
      background-color: #fdeee6 !important;
      color: #f66202;
    }
    .prediction {
      background-color: #409eff !important;
      border-color: #409eff !important;
      color: white;
      cursor: not-allowed;
    }
  }
  .tips {
    color: #f7914d;
    font-size: 14px;
    margin-bottom: 10px;
  }
}
.courseIntro {
  margin-top: 30px;
  .title {
    // padding: 0 15px 15px;
    border-left: 3px solid #f66604;
    margin-left: 15px;
    padding-left: 5px;
    margin-bottom: 10px;
  }
}
.actionBtn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 15px 15px 25px 15px;
  background-color: #fff;
  .icons {
    .icon {
      margin-right: 15px;
    }
  }
  .btn {
    background: #4196a2;
    font-family: "Microsoft YaHei", "微软雅黑";
    font-size: 16px;
    font-weight: bold;
    color: #ffffff;
    border-radius: 40px;
    text-align: center;
    width: 50%;
    padding: 8px 0;
  }
}
</style>



